package com.eascs.afterloancheck.dubbo;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.eascs.admin.common.service.ILoanCheckService;
import com.eascs.admin.common.vo.AfterLoanInfo;
import com.eascs.admin.common.vo.ModelResult;
import com.eascs.admin.o2o.loan.entity.DFEmailContentVO;
import com.eascs.admin.o2o.loan.entity.O2oLoanUserEntity;
import com.eascs.admin.o2o.loan.entity.O2oLoanapplyEntity;
import com.eascs.admin.o2o.loan.service.O2oLoanUserService;
import com.eascs.admin.o2o.loan.service.O2oLoanapplyService;
import com.eascs.afterloancheck.dao.Impl.LoanCheckDaoImpl;
import com.eascs.afterloancheck.entity.CheckLoanEntity;
import com.eascs.afterloancheck.service.LoanCheckServicce;
import com.eascs.app.log.Logger;
import com.eascs.app.log.LoggerFactory;
import com.eascs.common.util.UuidUtil;
import com.eascs.crm.common.service.ICustomerInfoService;
import com.eascs.crm.common.service.ICustomerShopService;
import com.eascs.crm.common.vo.QueryCustomerVO;
import com.eascs.crm.common.vo.ShopMarketMoneyRequest;
import com.eascs.crm.common.vo.ShopMarketMoneyResponse;
import com.eascs.notify.mail.MailNotifier;
import com.eascs.notify.mail.MailNotifyRequest;
import com.eascs.notify.mail.MailSendType;
import com.eascs.workflow.common.service.sequence.SequenceService;

@Service
public class LoanCheckTask implements ILoanCheckService {
	protected final Logger logger = LoggerFactory.getLogger(getClass());
	
	@Autowired
	private LoanCheckServicce loanCheckServicce;
	
	@Autowired
	LoanCheckDaoImpl loanCheckDao;
	
	@Autowired
	private O2oLoanapplyService o2oloanapplyService;
	
	@Autowired
	private O2oLoanUserService o2oLoanUserService;
	
	@Autowired
	private O2oLoanapplyService o2oLoanapplyService;
	
	@Reference(retries=3)
	ICustomerInfoService iCustomerInfoService;
	
	@Reference
	ICustomerShopService iCustomerShopService;
	
	@Reference
	private SequenceService SequenceService;
	
	@Reference
	private MailNotifier mailNotifier;
	
	private final static String REVISIT_TYPE_CHECK = "CHECK_LOAN_AFTER";
	
	public static List<AfterLoanInfo> abnormalBill = new ArrayList<AfterLoanInfo>();//自动发起异常单据
	
	@Override
	public  ModelResult<Boolean> autoStartUpLoanCheck() {
		logger.info("自动启动贷后定期检查，调用成功");
		ModelResult<Boolean> model = new ModelResult<>();
		List<AfterLoanInfo> loans = this.listAfterLoan();
		//启动流程
		if (null != loans && loans.size() > 0) {
			for (int i = 0, len = loans.size(); i < len; i++) {
					//70-89天内没有启动过流程的，自动发起流程
					CheckLoanEntity entity = loanCheckServicce.queryEntityByBillCode(loans.get(i).getBillCode());
					ModelResult<Boolean> startUp = new ModelResult<Boolean>();
					if (entity == null) {
						//未发起过流程情况
						startUp = this.startUp(loans.get(i), "inexistence");	
					} else {
						Date createDate = entity.getCreateDate();
				        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
				        //间隔天数
				        long minus = 0;
						try {
							minus = (sdf.parse(sdf.format(createDate)).getTime() - sdf.parse(sdf.format(loans.get(i).getPaymentTime())).getTime()) / (1000 * 60 * 60 * 24);
						} catch (ParseException e) {
							e.printStackTrace();
						}
						
				        if (minus >= 70) {
				        	continue;
				        } else {
				        	loans.get(i).setId(entity.getId());
				        	startUp = this.startUp(loans.get(i), "existence");	
				        }
					}
					model.setErrMsg(startUp.getErrMsg() == null ? "" : startUp.getErrMsg());
					if (!startUp.isSuccess() || !startUp.getModel()) {
						abnormalBill.add(loans.get(i));
						logger.info("启动贷后检查自动发起失败，参数有：启动时间：【{}】，状态：【{}】，流程类型：【{}】，异常原因：【{}】", new Date(), loans.get(i).getWfType(), "贷后定期检查", startUp.getErrMsg());
					}
			}
			logger.info("自动启动贷后定期检查完毕，其中异常发起总数【{}】", abnormalBill.size());
			if (abnormalBill.size() > 0) {
				sendEmail();
				abnormalBill = new ArrayList<AfterLoanInfo>();
				return model;
			}
			return model.withModel(Boolean.TRUE);
		} else {
			logger.info("自动启动贷后定期检查,调用成功,但未查询到需要自动发起流程的贷款单");
			return model.withModel(Boolean.TRUE);
		}
		
	}
	public ModelResult<Boolean> startUp(AfterLoanInfo vo, String status) {
		ModelResult<Boolean> modelResult=new ModelResult<>();
		CheckLoanEntity entity = this.getEntity(vo);
		CheckLoanEntity model = new CheckLoanEntity();
		if ("inexistence".equals(status)) {
			model = loanCheckDao.insertCheckLoanEntity(entity);
		} else if ("existence".equals(status)) {
			entity.setId(vo.getId());
		} else {
			model = null;
			return modelResult.withError("LoanCheckTask startUp", "不存在");
		}
		if (model != null) {
			com.eascs.workflow.common.vo.ModelResult<Boolean> startUpResult = loanCheckServicce.startUp(entity);
			if (startUpResult.isSuccess() && startUpResult.getModel()) {
				loanCheckDao.processRevisitStart(entity.getId());
				loanCheckDao.updateCreateTime(entity.getId());
				modelResult.setModel(true);
				return modelResult;
			}else {
				modelResult.withError("LoanCheckServicceImpl.error startUp()", startUpResult.getErrMsg());
				logger.info("LoanCheckServicceImpl.error.insertCheckLoanEntity(),exception:{}", startUpResult.getErrMsg());
				//修改状态
				modelResult.setModel(false);
				modelResult.setErrMsg(startUpResult.getErrMsg());
				loanCheckDao.deleteEntity(model);
			}
		}
		return modelResult;
	}
	
	public List<AfterLoanInfo> listAfterLoan() {
		String sql = "SELECT l.bill_code as billCode, l.operator_name as operatorName ,l.operator_no as operatorNo ,l.ltd as ltd,l.ltd_name as ltdName,l.wf_type as wfType,l.PAYMENT_TIME as paymentTime FROM	o2o_loanapply l WHERE	DATEDIFF(NOW(), "
				+ "l.create_date) >= 90 AND l.loan_flg = 'Y' AND L.bill_code NOT IN (SELECT bill_code FROM after_loan_check where wf_status = '2' )";
		List<AfterLoanInfo> findEntitys = loanCheckDao.findEntitys(sql, AfterLoanInfo.class,new Object[]{});
		return findEntitys; 
	}
	
	public CheckLoanEntity getEntity(AfterLoanInfo info) {
		CheckLoanEntity entity = new CheckLoanEntity();
		O2oLoanapplyEntity loanapply = o2oloanapplyService.fingByBillCode(info.getBillCode());
		entity.setCreateDate(new Date());
		entity.setBillCode(loanapply.getBillCode());
		entity.setRevisitType(REVISIT_TYPE_CHECK);
		entity.setLoanApplyNo(loanapply.getLoanapplyNo());
		entity.setOrgManager(loanapply.getOperatorName());
		entity.setOrgManagerId(loanapply.getOperatorNo());
		entity.setLoanType(loanapply.getLoanType());
		O2oLoanUserEntity loanUser = o2oLoanUserService.findById(loanapply.getLoanId(), loanapply.getLoanapplyNo());
		entity.setLoanUserName(loanUser.getUserFullName());
		entity.setLoanId(loanapply.getLoanId());
		entity.setLtd(o2oLoanapplyService.findById(loanapply.getLoanapplyNo()).getLtd());
		Integer loanNum = o2oLoanUserService.getLoanerCount(entity.getLoanId());
		entity.setLoanNumber(loanNum);
		QueryCustomerVO vo = new QueryCustomerVO();
		vo.setCustomer_id(entity.getLoanId());
		ShopMarketMoneyRequest shopMarketMoneyRequest = new ShopMarketMoneyRequest(); 
		shopMarketMoneyRequest.setCustomerId(entity.getLoanId());
		com.eascs.crm.common.vo.ModelResult<ShopMarketMoneyResponse> shopMarketMoney = iCustomerShopService.getShopMarketMoney(shopMarketMoneyRequest);
		ShopMarketMoneyResponse model = shopMarketMoney.getModel();
		if (shopMarketMoney.isSuccess() && model != null) {
			entity.setYearlySale(model.getTotalAmount() == null ? null : model.getTotalAmount().floatValue());
			entity.setStockMoney(model.getShoptock() == null ? null : model.getShoptock().floatValue());
		}
		String seq = SequenceService.getSeq("LOAN_CHECK_NO", 5, "DHDQJC-"+ new SimpleDateFormat("yyMMdd").format(new Date()));
		entity.setRevisitCode(seq);
		return entity;
	}
	
	/**
	 * 异常启动邮件发送
	 */
	public void sendEmail() {
		// 邮件发送需要的参数类
		MailNotifyRequest mailNotifyRequest = new MailNotifyRequest();
		mailNotifyRequest.setSystemCode("业务系统");
		mailNotifyRequest.setMailSendType(MailSendType.INSTANT);
		mailNotifyRequest.setRequestId(UuidUtil.generateShortUuid());
		mailNotifyRequest.setTitle("定期贷后检查流程发起异常通知");
		mailNotifyRequest.setRequestDateTime(new Date());
		mailNotifyRequest.setRecipientTo("zz9586@eascs.com,zz9549@eascs.com");
		mailNotifyRequest.setBizCode("DHDQJC-"+ new SimpleDateFormat("yyMMdd").format(new Date()));
		// 生成邮件内容
		DFEmailContentVO contentVo = new DFEmailContentVO();
		contentVo.setTitle("定期贷后检查流程发起异常通知");
		Calendar now = Calendar.getInstance();
		StringBuffer contentBuffer = new StringBuffer();
		contentBuffer.append(now.get(Calendar.YEAR) + "年" + (now.get(Calendar.MONTH) + 1) + "月" + now.get(Calendar.DAY_OF_MONTH) + "日");
		contentBuffer.append("自动启动定期贷后检查流程有"+abnormalBill.size()+"个异常,详细贷款单号为：");
		for (int i = 0; i < abnormalBill.size(); i++) {
			if (i == 0) {
				contentBuffer.append(abnormalBill.get(i).getBillCode());
			} else {
				contentBuffer.append("," + abnormalBill.get(i).getBillCode());
			}
		}
		mailNotifyRequest.setContent(contentBuffer.toString()); 
		mailNotifier.notify(mailNotifyRequest);
	}
}
